<template>
  <div id="createTouch" v-cloak>
    <el-dialog
      :title="isAdd ? '创建触达' : '编辑触达'"
      :visible.sync="dialogData.isShow"
      width="550px"
      :before-close="labelHandleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="130px"
        label-position="right"
      >
        <el-form-item label="触达用户" prop="preestablishCrowdId">
          <el-select
            value-key="reachsUserName"
            v-model="ruleForm.touchUser"
            placeholder="请选择"
          >
            <el-option
              v-for="item in preeList"
              :key="item.preestablishCrowdId"
              :label="item.reachsUserName"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触达时间" prop="touchTime">
          <el-date-picker
            v-model="ruleForm.touchTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="触达通道" prop="touchType">
          <el-select v-model="ruleForm.touchType" placeholder="请选择">
            <el-option
              v-for="item in touchTypeList"
              :key="item.touchType"
              :label="item.touchTypeName"
              :value="item.touchType"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--提示语-->
        <el-form-item v-if="showTip">
          <div class="tip">
            注意：消息{{ tipText }}是收费项目，{{ tipText }}将会产生实际费用！
          </div>
        </el-form-item>
        <!--标题-->
        <div v-if="showTitle">
          <el-form-item :label="curShow.title" prop="title">
            <el-input
              v-model="ruleForm.title"
              placeholder=""
              :maxlength="curShow.titleMax"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item v-if="showRadio" label="站内信接收类型" prop="acceptType">
          <el-radio
            v-for="item in acceptTypeList"
            :key="item.acceptType"
            v-model="ruleForm.acceptType"
            :label="item.acceptType"
          >
            {{ item.label }}
          </el-radio>
        </el-form-item>
        <div v-if="showImg">
          <el-form-item label="站内图片" prop="img">
            <uploadSingImg :imgUrl="ruleForm.img" @getImgUrl="getImgUrl">
              <template v-slot:imgInfo>注：JPG格式</template>
            </uploadSingImg>
          </el-form-item>
        </div>
        <div v-if="showTerminals">
          <el-form-item label="显示终端" prop="displayTerminals">
            <el-radio-group v-model="ruleForm.displayTerminals">
              <el-radio
                v-for="item in terminalTypeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <!--内容-->
        <el-form-item v-if="showConten" :label="curShow.content" prop="content">
          <el-input
            v-model="ruleForm.content"
            type="textarea"
            placeholder=""
            :maxlength="curShow.conMax"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">
          取 消
        </el-button>
        <el-button
          type="success"
          :loading="loading"
          @click.prevent="confirmLabel('ruleForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  editTouchDetail,
  getTouchDetail
} from '@/api/activeManagement/templatePage' // 接口
import uploadSingImg from '@common/uploadSingImg' // 导入
import { sysNormalDisable } from '@utils/dictionariesFunc'
export default {
  name: 'CreateTouch',
  msg: '触达设置-新增/编辑弹窗',
  components: {
    uploadSingImg
  },
  props: {
    dialogData: {
      type: Object,
      default: function() {
        return {
          isShow: false, // 默认隐藏
          type: 'add', // 默认新增
          params: '', // 编辑时，传递的参数
          preeListAdd: [] //预设用户规则列表，添加到触达用户列表后面
        }
      }
    }
  },
  data() {
    return {
      id: '', //活动id
      isAdd: true, // 新增-true,编辑-false
      eidtInitial: false, //编辑初始化赋值
      loading: false,
      ruleForm: {
        touchUser: {},
        preestablishCrowdId: 'PARTICIPATE_ACTIVITY_USER', //触达用户
        touchTime: '', //触达时间
        touchType: 'PUSH', //触达通道
        title: '', //标题
        acceptType: 'NOTICE', //触达类型
        img: '', //上传图片
        content: '', //推送内容
        displayTerminals: '' //显示终端
      },
      curShow: {
        title: '标题',
        titleMax: '10',
        content: '内容',
        conMax: '30'
      },
      pushShow: {
        title: '推送标题',
        titleMax: '20',
        content: '推送内容',
        conMax: '50'
      }, //触达通道-推送
      noticeShow: {
        title: '站内信标题',
        titleMax: '30',
        content: '站内信内容',
        conMax: '300'
      }, //触达通道-通知
      smsShow: {
        title: '',
        titleMax: '',
        content: '站内信内容',
        conMax: '300'
      }, //触达通道-短信
      tipText: '', //提示语
      rules: {
        touchTime: {
          required: true,
          message: '请选择触达时间',
          trigger: 'blur'
        },
        touchType: {
          required: true,
          message: '请选择触达通道',
          trigger: 'blur'
        },
        title: { required: true, message: '请输入标题', trigger: 'blur' },
        acceptType: {
          required: true,
          message: '请选择站内信接收类型',
          trigger: 'blur'
        },
        img: { required: true, message: '请上传图片', trigger: 'blur' },
        content: { required: true, message: '请输入内容', trigger: 'blur' },
        displayTerminals: {
          required: true,
          message: '请选择显示终端',
          trigger: 'blur'
        }
      },
      preeList: [
        {
          preestablishCrowdId: 'SUBMIT_POST_USER',
          reachsUserName: '提交作品的用户'
        },
        {
          preestablishCrowdId: 'PARTICIPATE_ACTIVITY_USER',
          reachsUserName: '参加活动的用户'
        },
        {
          preestablishCrowdId: 'CAN_PARTICIPATE_ACTIVITY_USER',
          reachsUserName: '发布活动的用户'
        }
      ], //触达用户列表
      touchTypeList: [
        { touchTypeName: '弹屏', touchType: 'BOMB_SCREEN' },
        { touchTypeName: '通知', touchType: 'NOTICE' },
        { touchTypeName: '短信', touchType: 'SMS' },
        { touchTypeName: '推送', touchType: 'PUSH' }
      ], //触达通道列表
      acceptTypeList: [
        {
          acceptType: 'NOTICE',
          label: '通知'
        },
        {
          acceptType: 'INTERACTS',
          label: '活动'
        }
      ],
      // 显示终端
      terminalTypeList: []
    }
  },
  computed: {
    showTerminals() {
      //显示条件：触达通道-“弹屏”
      return this.ruleForm.touchType === 'BOMB_SCREEN'
    },
    showImg() {
      //显示条件：触达通道-“弹屏”或者 触达通道“通知”且 站内信接收类型 “活动”
      let touchType = this.ruleForm.touchType
      let acceptType = this.ruleForm.acceptType
      let isShow =
        touchType === 'BOMB_SCREEN' ||
        (touchType === 'NOTICE' && acceptType === 'INTERACTS')
      if (!isShow) {
        this.ruleForm.img = ''
      }
      return isShow
    },
    showTitle() {
      //显示条件：触达通道-“通知”、“推送”
      let touchType = this.ruleForm.touchType
      if (touchType === 'NOTICE') {
        this.curShow = { ...this.noticeShow }
      }
      if (touchType === 'PUSH') {
        this.curShow = { ...this.pushShow }
      }
      return touchType === 'NOTICE' || touchType === 'PUSH'
    },
    showRadio() {
      //显示条件：触达通道-“通知”
      let touchType = this.ruleForm.touchType
      return touchType === 'NOTICE'
    },
    showTip() {
      //显示条件：触达通道-“短信”、“推送”
      let touchType = this.ruleForm.touchType
      if (touchType === 'SMS') {
        this.tipText = '短信'
      }
      if (touchType === 'PUSH') {
        this.tipText = '推送'
      }
      return touchType === 'SMS' || touchType === 'PUSH'
    },
    showConten() {
      //显示条件：触达通道-“通知”、“推送”、“短信”
      let touchType = this.ruleForm.touchType
      if (touchType === 'SMS') {
        this.curShow = { ...this.pushShow }
      }
      return (
        touchType === 'NOTICE' || touchType === 'PUSH' || touchType === 'SMS'
      )
    }
  },
  watch: {
    'ruleForm.touchType': {
      handler(newV, oldV) {
        if (this.eidtInitial) {
          this.eidtInitial = false
          return
        }
        //改变触达通道，内容清空
        this.ruleForm.title = ''
        this.ruleForm.acceptType = 'NOTICE'
        this.ruleForm.img = ''
        this.ruleForm.content = ''
        this.ruleForm.displayTerminals = ''
        this.isIndeterminate = false
        this.checkAll = false
        this.$refs.ruleForm.clearValidate()
      },
      deep: true
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this.isAdd = this.dialogData.type
    this.getStatusList()
    //触达用户列表添加数据
    if (this.dialogData.preeListAdd.length > 0) {
      this.preeList = this.preeList.concat(this.dialogData.preeListAdd)
    }
    if (this.isAdd) {
      this.ruleForm.touchUser = this.preeList[1]
    } else {
      if (this.dialogData.id) {
        this.getDetail(this.dialogData.id)
      } else {
        this.getSubItemDetail()
      }
    }
  },
  methods: {
    async getStatusList() {
      // 显示终端
      this.terminalTypeList = await sysNormalDisable('pop_screen_terminal')
    },
    /*编辑已提交保存的数据，获取详情*/
    getDetail() {
      getTouchDetail(
        this.id,
        this.dialogData.id,
        (response) => {
          this.eidtInitial = true
          this.ruleForm = Object.assign({}, { touchUser: {} }, response)
          //字符串转数组
          this.ruleForm.displayTerminals = response.displayTerminals[0]
          this.ruleForm.touchUser = this.preeList.find((item) => {
            return item.preestablishCrowdId === response.preestablishCrowdId
          })
        },
        (response) => {
          this.loading = false
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    /*编辑未提交保存的数据，获取详情*/
    getSubItemDetail() {
      this.eidtInitial = true
      this.ruleForm = Object.assign(
        {},
        { touchUser: {} },
        this.dialogData.params
      )
      this.ruleForm.touchUser = {
        preestablishCrowdId: this.dialogData.params.preestablishCrowdId,
        reachsUserName: this.dialogData.params.reachsUserName
      }
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    // 取消
    cancelLabel() {
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.type = ''
      this.dialogData.id = ''
      this.dialogData.i = -1
      this.dialogData.params = ''
    },
    /*获取图片url*/
    getImgUrl(url) {
      this.ruleForm.img = url
    },
    // 提交
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return
        }
        /*console.log("通过校验")*/
        let touchType = this.ruleForm.touchType
        if (touchType === 'SMS' || touchType === 'PUSH') {
          //“短信”、“推送”为收费项目
          this.$confirm(
            `<span style="color:red;font-weight:bold;">消息${this.tipText}是收费项目，${this.tipText}将会产生实际费用！ 确定要使用 "${this.tipText}" 方式发布通知吗？</span>`,
            '系统提示',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '我确认',
              cancelButtonText: '我再想想',
              type: 'warning'
            }
          ).then(() => {
            this.subForm()
          })
        } else {
          this.subForm()
        }
      })
    },
    subForm() {
      let obj = { ...this.ruleForm }
      obj.preestablishCrowdId = obj.touchUser.preestablishCrowdId
      obj.reachsUserName = obj.touchUser.reachsUserName
      obj.displayTerminals = obj.displayTerminals ? [obj.displayTerminals] : []
      delete obj.touchUser
      if (this.isAdd) {
        //新增
        this.$emit('addSubList', this.ruleForm)
        console.log(this.ruleForm, 'sssssssss')
        this.cancelLabel()
      } else {
        if (this.dialogData.id) {
          //编辑保存数据
          editTouchDetail(
            this.id,
            this.dialogData.id,
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning(response.message)
            }
          )
        } else {
          //编辑未保存数据
          this.$emit('editSubList', {
            obj: this.ruleForm,
            i: this.dialogData.i
          })
          this.cancelLabel()
        }
      }
    }
  }
}
</script>
<style lang="less">
#createTouch {
  .tip {
    font-size: 18px;
    color: #f00;
    font-weight: bold;
  }
}
</style>
